<?php

namespace app\wechat\controller;

use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;

class Login extends Common
{

    /**
     * 进小程序时授权
     * @return \think\response\Json
     */
    public function login()
    {

        $wechatCode = $this->request->post('wechatCode');
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');
        $pid = $this->request->post('pid');
        $appid = config("constants.miniProgramConfig.appid");

        // 根据code获取openid
        $authResult = $this->miniProgram->auth->session($wechatCode);

        if (!isset($authResult['session_key'])) {
            return errorReturn('errorWechat.errorAuthCode');
        }

        $sessionKey = $authResult['session_key'];

        $decryptResult = decryptData($sessionKey, $appid,
            $encryptedData, $iv, $wechatResult);

        if (!$decryptResult) {
            return errorReturn('errorWechat.errorAuthCode');
        }

        $openid = $wechatResult["openId"];
        $nickname = $wechatResult["nickName"];
        $headimgurl = $wechatResult["avatarUrl"];
        $unionid = $wechatResult["unionId"];

        // 调用每日优选接口
        $yxRegisterResult = yxShopkeepersRegister($nickname,
            $headimgurl, $unionid, $openid);

        if(!$yxRegisterResult["success"]) {
            $returnError = config("errorWechat.errorYxService");
            $returnError["message"] = $yxRegisterResult["msg"];
            return json($returnError);
        }

        // 查询是否已存在此用户
        $customer = $this->customerService->findByOpenid($openid);

        // 定义返回数据类型
        $returnData = [
            "token" => isNullOrEmpty($customer) ? '' : $customer['token'],
            "pid" => isNullOrEmpty($customer) ? '' : $customer['yx_pid']
        ];

        // 如果不存在此用户
        if (isNullOrEmpty($customer)) {

            Db::startTrans();

            try {

                if (!isNullOrEmpty($pid)) {

                    $parentCustomer = $this->customerService
                        ->findByYxPid($pid);

                    if (isNullOrEmpty($parentCustomer)) {
                        return errorReturn('errorWechat.errorPidNotFound');
                    }

                    $customerData["parent_customer_id"] = $parentCustomer["id"];
                    $customerData["parent_yx_pid"] = $parentCustomer["yx_pid"];

                    // 更新上级用户的团队总人数
                    $parentCustomerData["total_group_number"] =
                        $parentCustomer["total_group_number"] + 1;

//                    $this->customerService->updateByIdAndData(
//                        $parentCustomer["id"], $parentCustomerData);
                    // 一个诡异的问题，用 updateByIdAndData 会吧新用户的 total_group_number一并更新
                    Db::table("xd_customer")
                        ->where('id', $parentCustomer['id'])
                        ->update($parentCustomerData);

                    if (!isNullOrEmpty(
                        $parentCustomer["parent_customer_id"])) {

                        $topCustomer = $this->customerService
                            ->findById($parentCustomer["parent_customer_id"]);

                        if (!isNullOrEmpty($topCustomer)) {

                            $customerData["top_customer_id"] = $topCustomer["id"];
                            $customerData["top_yx_pid"] = $topCustomer["yx_pid"];

                            // 更新顶级用户的总人数
                            $topCustomerData["total_group_number"] =
                                $topCustomer["total_group_number"] + 1;

//                            $this->customerService->updateByIdAndData(
//                                $topCustomer["id"], $topCustomerData);
                            // 一个诡异的问题，用 updateByIdAndData 会吧新用户的 total_group_number一并更新
                            Db::table("xd_customer")
                                ->where('id', $topCustomer['id'])
                                ->update($topCustomerData);

                        }
                    }

                }

                $customerData['yx_pid'] = $yxRegisterResult['info']['pid'];
                $customerData['openid'] = $openid;
                $customerData['unionid'] = $unionid;
                $customerData['nickname'] = $nickname;
                $customerData['headimgurl'] = $headimgurl;
                $customerData['sex'] = '';
                $customerData['token'] = createUuid();
                $customerData['home_json'] = '[]';
                $customerData['newest_list_json'] = '[]';
                $customerData['reg_date'] = getCurrentDate();

                $this->customerService->saveByData($customerData);

                $returnData['token'] = $customerData['token'];
                $returnData['pid'] = $customerData['yx_pid'];

                Db::commit();

            } catch (PDOException $exception) {

                Db::rollback();

                return errorReturn('errorWechat.errorService');

            }
        }

        return successReturn($returnData);

    }

}